/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.jzgxx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.datasource.FlexDataSource;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.zaxxer.hikari.HikariDataSource;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Transaction;
import vip.xiaonuo.biz.modular.jzgxx.entity.JwJzgxx;
import vip.xiaonuo.biz.modular.jzgxx.mapper.JwJzgxxMapper;
import vip.xiaonuo.biz.modular.jzgxx.param.JwJzgxxAddParam;
import vip.xiaonuo.biz.modular.jzgxx.param.JwJzgxxEditParam;
import vip.xiaonuo.biz.modular.jzgxx.param.JwJzgxxIdParam;
import vip.xiaonuo.biz.modular.jzgxx.param.JwJzgxxPageParam;
import vip.xiaonuo.biz.modular.jzgxx.service.JwJzgxxService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.common.util.CommonDbUtil;
import vip.xiaonuo.dev.modular.config.service.DevConfigService;
import vip.xiaonuo.sys.modular.role.entity.SysRole;
import vip.xiaonuo.sys.modular.role.param.SysRoleGrantUserParam;
import vip.xiaonuo.sys.modular.role.service.impl.SysRoleServiceImpl;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.param.SysUserImportParam;
import vip.xiaonuo.sys.modular.user.service.impl.SysUserServiceImpl;

import java.sql.SQLTimeoutException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * 教工信息Service接口实现类
 *
 * @author lrw
 * @date  2025/02/01 20:46
 **/
@Component

public class JwJzgxxServiceImpl extends ServiceImpl<JwJzgxxMapper, JwJzgxx> implements JwJzgxxService {
    @Inject
    public DevConfigService devConfigService;
@Inject
private SysUserServiceImpl sysUserServiceImpl;
@Inject
private SysRoleServiceImpl sysRoleServiceImpl;

    /**
     *查询教务系统中的教职工信息
     * 动态连接教务系统oracle数据源
     * @param jwJzgxxPageParam
     * @return
     */
    @Override
    public Page<JwJzgxx> page(JwJzgxxPageParam jwJzgxxPageParam) {
        String jgh=jwJzgxxPageParam.getJgh();
        String xm=jwJzgxxPageParam.getXm();
        String sfzh=jwJzgxxPageParam.getSfzjh();
        String dwmc=jwJzgxxPageParam.getDwmc();
        String dqzt=jwJzgxxPageParam.getDqzt();
        if(ObjectUtil.isEmpty(jgh) && ObjectUtil.isEmpty(xm) && ObjectUtil.isEmpty(sfzh) && ObjectUtil.isEmpty(dwmc)) return null;
        try {
            //动态添加新的数据源
            HikariDataSource ds = CommonDbUtil.getTmpDs("/jwdb.properties");
            FlexGlobalConfig.getDefaultConfig().getDataSource().addDataSource("jw", ds);
            DataSourceKey.use("jw");//使用新的数据源
            //SqlUtils sqlUtils=SqlUtils.of(dataSource);
            //List<JwJzgxx> jwJzgxxlist =sqlUtils.sql("select dwmc,jgh,xm,sfzjh,xb,csrq,jszc from V_JZGXX where dqzt='在职' and dwmc='信息学院' order by jgh").queryRowList().toBeanList(JwJzgxx.class);
            QueryWrapper queryWrapper = new QueryWrapper();

            if (ObjectUtil.isNotEmpty(jgh)) {
                queryWrapper.like(JwJzgxx::getJgh, jgh);
            }
            if (ObjectUtil.isNotEmpty(xm)) {
                queryWrapper.like(JwJzgxx::getXm, xm);
            }
            if (ObjectUtil.isNotEmpty(sfzh)) {
                queryWrapper.like(JwJzgxx::getSfzjh, sfzh);
            }
            if (ObjectUtil.isNotEmpty(dwmc)) {
                queryWrapper.like(JwJzgxx::getDwmc, dwmc);
            }
            if (ObjectUtil.isNotEmpty(dqzt)) {
                queryWrapper.like(JwJzgxx::getDqzt, dqzt);
            }
            if (ObjectUtil.isAllNotEmpty(jwJzgxxPageParam.getSortField(), jwJzgxxPageParam.getSortOrder())) {
                CommonSortOrderEnum.validate(jwJzgxxPageParam.getSortOrder());
                queryWrapper.orderBy(StrUtil.toUnderlineCase(jwJzgxxPageParam.getSortField()), jwJzgxxPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()));
            } else {
                queryWrapper.orderBy(JwJzgxx::getJgh);
            }
            return this.page(CommonPageRequest.defaultPage(), queryWrapper);
        }catch (Exception e){
            return null;
        }finally{
            DataSourceKey.clear();
        }
    }

    public List<JwJzgxx> list(JwJzgxxPageParam jwJzgxxPageParam) {
        String jgh=jwJzgxxPageParam.getJgh();
        String xm=jwJzgxxPageParam.getXm();
        String sfzh=jwJzgxxPageParam.getSfzjh();
        String dwmc=jwJzgxxPageParam.getDwmc();
        String dqzt=jwJzgxxPageParam.getDqzt();
        //if(ObjectUtil.isEmpty(jgh) && ObjectUtil.isEmpty(xm) && ObjectUtil.isEmpty(sfzh) && ObjectUtil.isEmpty(dwmc)) return null;
        try {
            //动态添加新的数据源
            HikariDataSource ds = CommonDbUtil.getTmpDs("/jwdb.properties");
            FlexGlobalConfig.getDefaultConfig().getDataSource().addDataSource("jw", ds);
            DataSourceKey.use("jw");//使用新的数据源
            //SqlUtils sqlUtils=SqlUtils.of(dataSource);
            //List<JwJzgxx> jwJzgxxlist =sqlUtils.sql("select dwmc,jgh,xm,sfzjh,xb,csrq,jszc from V_JZGXX where dqzt='在职' and dwmc='信息学院' order by jgh").queryRowList().toBeanList(JwJzgxx.class);
            QueryWrapper queryWrapper = new QueryWrapper();

            if (ObjectUtil.isNotEmpty(jgh)) {
                queryWrapper.like(JwJzgxx::getJgh, jgh);
            }
            if (ObjectUtil.isNotEmpty(xm)) {
                queryWrapper.like(JwJzgxx::getXm, xm);
            }
            if (ObjectUtil.isNotEmpty(sfzh)) {
                queryWrapper.like(JwJzgxx::getSfzjh, sfzh);
            }
            if (ObjectUtil.isNotEmpty(dwmc)) {
                queryWrapper.like(JwJzgxx::getDwmc, dwmc);
            }
            if (ObjectUtil.isNotEmpty(dqzt)) {
                queryWrapper.like(JwJzgxx::getDqzt, dqzt);
            }
            if (ObjectUtil.isAllNotEmpty(jwJzgxxPageParam.getSortField(), jwJzgxxPageParam.getSortOrder())) {
                CommonSortOrderEnum.validate(jwJzgxxPageParam.getSortOrder());
                queryWrapper.orderBy(StrUtil.toUnderlineCase(jwJzgxxPageParam.getSortField()), jwJzgxxPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()));
            } else {
                queryWrapper.orderBy(JwJzgxx::getJgh);
            }
            return this.list( queryWrapper);
        }catch (Exception e){
            return null;
        }finally{
            DataSourceKey.clear();
        }
    }
    /**
     * 同步更新教职工信息
     * @param jwJzgxxPageParam
     * @return
     */
    @Override
    public JSONObject syncupd(JwJzgxxPageParam jwJzgxxPageParam) {
        HikariDataSource ds = CommonDbUtil.getTmpDs("/jwdb.properties");
        FlexGlobalConfig.getDefaultConfig().getDataSource().addDataSource("jw", ds);
        DataSourceKey.use("jw");//使用新的数据源
        QueryWrapper queryWrapper = new QueryWrapper();
        if(ObjectUtil.isNotEmpty(jwJzgxxPageParam.getJgh())) {
            queryWrapper.like(JwJzgxx::getJgh, jwJzgxxPageParam.getJgh());
        }
        if(ObjectUtil.isNotEmpty(jwJzgxxPageParam.getXm())) {
            queryWrapper.like(JwJzgxx::getXm, jwJzgxxPageParam.getXm());
        }
        if(ObjectUtil.isNotEmpty(jwJzgxxPageParam.getSfzjh())) {
            queryWrapper.like(JwJzgxx::getSfzjh, jwJzgxxPageParam.getSfzjh());
        }
        if(ObjectUtil.isNotEmpty(jwJzgxxPageParam.getDqzt())) {
            queryWrapper.eq(JwJzgxx::getDqzt, jwJzgxxPageParam.getDqzt());
        }
        if(ObjectUtil.isNotEmpty(jwJzgxxPageParam.getDwmc())) {
            queryWrapper.like(JwJzgxx::getDwmc, jwJzgxxPageParam.getDwmc());
        }
        List<JwJzgxx> jwJzgxxList = this.list(queryWrapper);
        FlexGlobalConfig.getDefaultConfig().getDataSource().removeDatasource("jw");
        //DataSourceKey.use("snowy");
        /*finally {
            DataSourceKey.clear();
        }*/
        return doImport(jwJzgxxList);
    }

    /**
     * 逐一更新
     * @param jwJzgxxList
     * @return
     */
    @Transaction
    public JSONObject doImport(List<JwJzgxx> jwJzgxxList){
        try {
            int successCount = 0;
            int errorCount = 0;
            JSONArray errorDetail = JSONUtil.createArray();
            //提前读入所有用户，减少反复查询数据库；当用户数据较多时，内存压力会较大
            String orgName=devConfigService.getValueByKey("ORG_NAME");
            List<SysUser> allUserList = sysUserServiceImpl.list();
            for (int i = 0; i < jwJzgxxList.size(); i++) {
                SysUserImportParam sysUserImportParam = new SysUserImportParam();
                JwJzgxx jwJzgxx = jwJzgxxList.get(i);
                sysUserImportParam.setAccount(jwJzgxx.getJgh());
                sysUserImportParam.setName(jwJzgxx.getXm());
                sysUserImportParam.setOrgName(orgName+"-"+jwJzgxx.getDwmc());
                sysUserImportParam.setIdCardNumber(jwJzgxx.getSfzjh());
                sysUserImportParam.setPositionName("教师");
                JSONObject jsonObject = sysUserServiceImpl.doImport(allUserList, sysUserImportParam, i);
                if (jsonObject.getBool("success")) {
                    successCount += 1;
                    String userid = jsonObject.getStr("id");
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq(SysRole::getName,"教师");
                    SysRole sysRole=sysRoleServiceImpl.getOne(queryWrapper);
                    String roleid=sysRole.getId();//String roleid=sysRoleServiceImpl.queryEntity("教师").getId();
                    SysRoleGrantUserParam sysRoleGrantUserParam=new SysRoleGrantUserParam();
                    sysRoleGrantUserParam.setId(roleid);
                    sysRoleGrantUserParam.setGrantInfoList(Arrays.asList(userid));
                    sysRoleServiceImpl.grantUser(sysRoleGrantUserParam);
                } else {
                    errorCount += 1;
                    errorDetail.add(jsonObject);
                }
            }
            return JSONUtil.createObj()
                    .set("totalCount", jwJzgxxList.size())
                    .set("successCount", successCount)
                    .set("errorCount", errorCount)
                    .set("errorDetail", errorDetail);
        } catch (Exception e) {
            throw new CommonException("教师同步失败");
        }
    }
    @Transaction
    @Override
    public void add(JwJzgxxAddParam jwJzgxxAddParam) {
        JwJzgxx jwJzgxx = BeanUtil.toBean(jwJzgxxAddParam, JwJzgxx.class);
        this.save(jwJzgxx);
    }

    @Transaction
    @Override
    public void edit(JwJzgxxEditParam jwJzgxxEditParam) {
        JwJzgxx jwJzgxx = this.queryEntity(jwJzgxxEditParam.getJgh());
        BeanUtil.copyProperties(jwJzgxxEditParam, jwJzgxx);
        this.updateById(jwJzgxx);
    }

    @Transaction
    @Override
    public void delete(List<JwJzgxxIdParam> jwJzgxxIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(jwJzgxxIdParamList, JwJzgxxIdParam::getJgh));
    }

    @Override
    public JwJzgxx detail(JwJzgxxIdParam jwJzgxxIdParam) {
        return this.queryEntity(jwJzgxxIdParam.getJgh());
    }

    @Override
    public JwJzgxx queryEntity(String id) {
        JwJzgxx jwJzgxx = this.getById(id);
        if(ObjectUtil.isEmpty(jwJzgxx)) {
            throw new CommonException("教工信息不存在，id值为：{}", id);
        }
        return jwJzgxx;
    }
}
